﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VietImage.Models;
using VietImage.Roles;
using System.IO;

namespace VietImageSoftware
{
	/// <summary>
	/// Interaction logic for ManageCategoryForm.xaml
	/// </summary>
	public partial class ManageCategoryForm : Window
    {
        private ReadXMLHelper xmlHelper;

        internal ReadXMLHelper XmlHelper
        {
            get { return xmlHelper; }
            set { xmlHelper = value; }
        }

        private RegisteredUserRole userRole;

        public RegisteredUserRole UserRole
        {
            get { return userRole; }
            set { userRole = value; }
        }

        private Category currentCategory;

        public Category CurrentCategory
        {
            get { return currentCategory; }
            set { currentCategory = value; }
        }

        private String txtTitle;

        public String TxtTitle
        {
            get { return txtTitle; }
            set { txtTitle = value; }
        }

        private String txtManage;

        public String TxtManage
        {
            get { return txtManage; }
            set { txtManage = value; }
        }

        private Category parentCategory;

        public Category ParentCategory
        {
            get { return parentCategory; }
            set { parentCategory = value; }
        }



        private List<DetailCategory> lDetailCategories;

		public ManageCategoryForm()
		{
			this.InitializeComponent();
			// Insert code required on object creation below this point.
		}

        #region Manage Category

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            xmlHelper = new ReadXMLHelper();
            xmlHelper.ReadXML();
            btnMCManage.Content = txtManage;
            txbMCTitle.Text = txtTitle;
            if (txbMCTitle.Text.Contains("Create"))
            {
                btnMCChoosePrimaryImage.IsEnabled = false;
            }
            if (txbMCTitle.Text.Contains("Create") && !txbMCTitle.Text.Contains("sub"))
            {
                lblMCCategory.Visibility = Visibility.Hidden;
                txtMCCategory.Visibility = Visibility.Hidden;
                dpMCTakenTime.IsEnabled = false;
                cbMCCountry.IsEnabled = false;
                txtMCCity.IsEnabled = false;
            }
            else
            {
                if (parentCategory != null)
                {
                    dpMCTakenTime.IsEnabled = true;
                    cbMCCountry.IsEnabled = true;
                    txtMCCity.IsEnabled = true;
                }
                else
                {
                    dpMCTakenTime.IsEnabled = false;
                    cbMCCountry.IsEnabled = false;
                    txtMCCity.IsEnabled = false;
                }
            }
            if (currentCategory != null)
                lDetailCategories = currentCategory.GetDetails();
            else
            {
                currentCategory = new Category();
                lDetailCategories = new List<DetailCategory>();
                foreach (VietImage.Models.Language l in VietImage.Models.Language.GetList())
                {
                    DetailCategory dc = new DetailCategory();
                    dc.ID_Language = l.ID;
                    dc.Name = "";
                    dc.Tag = "";
                    dc.Description = "";
                    lDetailCategories.Add(dc);
                }
            }

            int index = 0;
            cbMCLanguage.Items.Clear();
            List<VietImage.Models.Language> lLang = VietImage.Models.Language.GetList();
            for (int i = 0; i < lLang.Count;i++ )
            {
                if (lLang[i].ID == userRole.ID_Language)
                    index = i;
                cbMCLanguage.Items.Add(lLang[i]);
            }
            cbMCLanguage.SelectedValuePath = "ID";
            cbMCLanguage.DisplayMemberPath = "Language1";
            cbMCLanguage.SelectedIndex = index;

            if (!currentCategory.IsParent)
            {
                index = 0;
                cbMCCountry.Items.Clear();
                foreach (Country i in Country.GetList())
                {
                    if (txbMCTitle.Text.ToString().Contains("Edit"))
                        if (i.ID != currentCategory.City.ID_Country)
                            index++;
                    cbMCCountry.Items.Add(i);
                }
                cbMCCountry.SelectedValuePath = "ID";
                cbMCCountry.DisplayMemberPath = "Name";
                cbMCCountry.SelectedValue = index;
            }

            if (txbMCTitle.Text.ToString().Contains("Edit"))
            {
                if (!currentCategory.IsParent)
                {
                    dpMCTakenTime.SelectedDate = currentCategory.TakenTime;
                    btnMCChooseParentCategories.Visibility = Visibility.Visible;
                }
                else
                {
                    btnMCChooseParentCategories.Visibility = Visibility.Hidden;
                }
                lDetailCategories = currentCategory.Details;
            }
            else
            {
                dpMCTakenTime.SelectedDate = DateTime.Now;
                cbMCCountry.SelectedValue = 217;
                btnMCChooseParentCategories.Visibility = Visibility.Hidden;
            }

            if (!btnMCManage.Content.ToString().Contains("Edit"))
            {
                txtMCAuthor.Text = xmlHelper.CategoryAuthor;
                if (txtMCAuthor.Text == "")
                {
                    DetailUser du = userRole.UserInfo.GetDetail(userRole.ID_Language);
                    if (userRole.ID_Language != 2)
                        txtMCAuthor.Text = du.Firstname + " " + du.Lastname;
                    else
                        txtMCAuthor.Text = du.Lastname + " " + du.Firstname;
                }
            }
            else
            {
                if (currentCategory.IsParent)
                    txtMCAuthor.Text = currentCategory.Author;
                else
                {
                    txtMCAuthor.Text = currentCategory.Author;
                    txtMCCity.Text = currentCategory.GetCity().Name;
                    cbMCCountry.SelectedValue = currentCategory.GetCity().ID_Country;
                }
            }

            if (currentCategory.PrimaryImage != null)
            {
                using (var stream = new MemoryStream(currentCategory.PrimaryImage.ToArray()))
                {
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    bitmap.StreamSource = stream;
                    bitmap.StreamSource.Position = 0;
                    bitmap.EndInit();
                    bitmap.Freeze();

                    imgMCPrimaryImage.Source = bitmap;
                }
            }
            
        }

        private void btnMCCancel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Close();
        }

        private void btnMCManage_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Manage();
            if (txbMCTitle.Text.ToString().Contains("Edit") && txbMCTitle.Text.ToString().Contains("sub") && currentCategory != null)
            {
                ChooseParentCategoriesForm form = new ChooseParentCategoriesForm();
                form.UserRole = userRole;
                form.CurrentCategory = currentCategory;
                form.ShowDialog();
                currentCategory = form.CurrentCategory;
            }
        }

        private void Manage()
        {
            List<ErrorItem> errorList = new List<ErrorItem>();
            OwnerRole role = (OwnerRole)userRole;


            VietImage.Models.Language ls = (VietImage.Models.Language)cbMCLanguage.SelectedItem;
            try
            {
                if (currentCategory.GetDetail(ls.ID).Name != txtMCName.Text)
                {
                    if (Category.Existed(txtMCName.Text, ls.ID))
                    {
                        errorList.Add(new ErrorItem("ErrorMessage", "The category name is existed!"));
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                        return;
                    }
                }
            }
            catch
            {
                foreach (Language l in VietImage.Models.Language.GetList())
                {
                    foreach (DetailCategory dc in lDetailCategories)
                    {
                        if (Category.Existed(txtMCName.Text, l.ID))
                        {
                            errorList.Add(new ErrorItem("ErrorMessage", "The category name is existed!"));
                            MessageForm form = new MessageForm();
                            form.ErrorList = errorList;
                            form.ShowDialog();
                            return;
                        }
                    }
                }
            }

            if (txtMCAuthor.Text == "")
            {
                errorList.Add(new ErrorItem("ErrorMessage", "Please fill the author name!"));
                MessageForm form = new MessageForm();
                form.ErrorList = errorList;
                form.ShowDialog();
                return;
            }

            xmlHelper.CategoryAuthor = txtMCAuthor.Text;
            xmlHelper.WriteXML();

            foreach (Language l in VietImage.Models.Language.GetList())
            {
                foreach (DetailCategory dc in lDetailCategories)
                {
                    if (dc.ID_Language == l.ID && dc.Name == "")
                    {
                        errorList.Add(new ErrorItem("ErrorMessage", "Please fill the category name for two languages!"));
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                        return;
                    }
                }
            }

            if (txbMCTitle.Text.Contains("Create"))
            {
                Category c = new Category();
                c.Author = txtMCAuthor.Text;
                if (txbMCTitle.Text.ToString().Contains("sub"))
                {
                    City city = new City();
                    city.Name = txtMCCity.Text;
                    city.ID_Country = int.Parse(cbMCCountry.SelectedValue.ToString());
                    errorList = City.Insert(ref city, 1);
                    if (errorList.Count > 0)
                    {
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                        return;
                    }
                    txtMCCity.Text = city.Name;
                    c.ID_City = city.ID;
                    c.TakenTime = dpMCTakenTime.SelectedDate;
                }
                else
                    c.ID_City = 0;

                currentCategory = c;

                MessageForm mForm = new MessageForm();
                mForm.UserRole = userRole;
                mForm.HaveOKButton = true;
                mForm.TxtOK = "Yes";
                mForm.TxtCancel = "No";
                mForm.TxtTitle = "Warning";
                mForm.TxtMessage = "Do you want to create this category?";
                mForm.CurrentCategory = currentCategory;
                mForm.DetailCategories = lDetailCategories;
                mForm.ShowDialog();
                if (parentCategory != null)
                    parentCategory.InsertSubCategory(userRole.UserInfo.ID, mForm.CurrentCategory.ID, userRole.ID_Language);
                currentCategory = mForm.CurrentCategory;
                lDetailCategories = mForm.DetailCategories;
            }
            else if (txbMCTitle.Text.ToString().Contains("Edit"))
            {
                if (txtMCCity.Text == "")
                {
                    if (txtMCAuthor.Text == "")
                    {
                        errorList.Add(new ErrorItem("ErrorMessage", "Please fill the city name!"));
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                        return;
                    }
                }

                currentCategory.Author = txtMCAuthor.Text;

                if (txbMCTitle.Text.ToString().Contains("sub"))
                {
                    City city = new City();
                    city.Name = txtMCCity.Text;
                    city.ID_Country = int.Parse(cbMCCountry.SelectedValue.ToString());
                    errorList = City.Insert(ref city, 1);
                    if (errorList.Count > 0)
                    {
                        MessageForm form = new MessageForm();
                        form.ErrorList = errorList;
                        form.ShowDialog();
                        return;
                    }
                    txtMCCity.Text = city.Name;
                    currentCategory.ID_City = city.ID;
                    currentCategory.TakenTime = dpMCTakenTime.SelectedDate;
                }
                else
                    currentCategory.ID_City = 0;

                MessageForm mForm = new MessageForm();
                mForm.UserRole = userRole;
                mForm.HaveOKButton = true;
                mForm.TxtOK = "Yes";
                mForm.TxtCancel = "No";
                mForm.TxtTitle = "Warning";
                mForm.TxtMessage = "Do you want to edit this category?";
                mForm.CurrentCategory = currentCategory;
                mForm.DetailCategories = lDetailCategories;
                mForm.ShowDialog();
                currentCategory = mForm.CurrentCategory;
                lDetailCategories = mForm.DetailCategories;
            }
        }

        private void cbMCLanguage_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            int lang = 0;
            if (cbMCLanguage.SelectedIndex >= 0)
            {
                VietImage.Models.Language l = (VietImage.Models.Language)cbMCLanguage.Items[cbMCLanguage.SelectedIndex];
                lang = l.ID;
                foreach (DetailCategory dc in lDetailCategories)
                {
                    if (dc.ID_Language == lang)
                    {
                        txtMCDescription.Text = dc.Description;
                        txtMCName.Text = dc.Name;
                        txtMCTag.Text = dc.Tag;
                        break;
                    }
                }
            }
        }

        private void btnMCChooseParentCategories_Click(object sender, RoutedEventArgs e)
        {
            if (!txbMCTitle.Text.Contains("Edit"))
                Manage();
            if (currentCategory != null)
            {
                ChooseParentCategoriesForm form = new ChooseParentCategoriesForm();
                form.UserRole = userRole;
                form.CurrentCategory = currentCategory;
                form.ShowDialog();
                currentCategory = form.CurrentCategory;
            }
        }

        private void txtMCName_TextChanged(object sender, TextChangedEventArgs e)
        {
            int lang = 0;
            if (cbMCLanguage.SelectedIndex >= 0)
            {
                VietImage.Models.Language l = (VietImage.Models.Language)cbMCLanguage.Items[cbMCLanguage.SelectedIndex];
                lang = l.ID;
                foreach (DetailCategory dc in lDetailCategories)
                {
                    if (dc.ID_Language == lang)
                    {
                        dc.Name = txtMCName.Text;
                        break;
                    }
                }
            }
        }

        private void txtMCDescription_TextChanged(object sender, TextChangedEventArgs e)
        {
            int lang = 0;
            if (cbMCLanguage.SelectedIndex >= 0)
            {
                VietImage.Models.Language l = (VietImage.Models.Language)cbMCLanguage.Items[cbMCLanguage.SelectedIndex];
                lang = l.ID;
                foreach (DetailCategory dc in lDetailCategories)
                {
                    if (dc.ID_Language == lang)
                    {
                        dc.Description = txtMCDescription.Text;
                        break;
                    }
                }
            }
        }

        private void txtMCTag_TextChanged(object sender, TextChangedEventArgs e)
        {
            int lang = 0;
            if (cbMCLanguage.SelectedIndex >= 0)
            {
                VietImage.Models.Language l = (VietImage.Models.Language)cbMCLanguage.Items[cbMCLanguage.SelectedIndex];
                lang = l.ID;
                foreach (DetailCategory dc in lDetailCategories)
                {
                    if (dc.ID_Language == lang)
                    {
                        dc.Tag = txtMCTag.Text;
                        break;
                    }
                }
            }
        }
        #endregion


        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

            xmlHelper.WriteXML();
        }

        private void gridManageCategory_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            try
            {
                this.DragMove();
            }
            catch (Exception ex)
            {
            }

        }

        private void btnMCChoosePrimaryImage_Click(object sender, RoutedEventArgs e)
        {
            if (currentCategory != null)
            {
                ChoosePrimaryImageForm form = new ChoosePrimaryImageForm();
                form.UserRole = userRole;
                form.CurrentCategory = currentCategory;
                form.ShowDialog();
            }
        }
	}
}